package com.novunda.platform.repositories;

import com.google.gson.JsonSyntaxException;
import com.novunda.platform.common.exception.NovException;
import com.novunda.platform.common.reponse.CommonResponse;
import com.novunda.platform.common.reponse.QrCodeStatusResponse;
import com.novunda.tca.tdk.TCAClient;
import com.novunda.tca.tdk.auth.DefaultCredentialProvider;
import com.novunda.tca.tdk.domain.ApplyQrCodeResponse;
import com.novunda.tca.tdk.domain.DeviceInfoResponse;
import com.novunda.tca.tdk.http.HttpMethod;
import com.novunda.tca.tdk.http.URLConnectionClient;
import com.novunda.tca.tdk.http.request.TCAClientRequest;
import com.novunda.tca.tdk.http.request.TCAHeaders;
import com.novunda.tca.tdk.http.response.TCAClientResponse;
import com.novunda.tca.tdk.utils.BusinessTypeEnum;
import com.novunda.tca.tdk.utils.ConfigResource;
import com.novunda.tca.tdk.utils.GsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

/**
 * ..
 * 接口获取绑定设备信息
 *
 * @author yangg
 * @since 2016/9/12.
 */
@Repository
public class CenterRepository {

    @Autowired
    private Environment env;
    //请求格式
    private static final String HEADER_TYPE = "application/x-www-form-urlencoded";
    //客户端参数名
    private static final String CLIENT_ID = "client_id";


    /**
     * 根据用户名获取对应的绑定设备信息
     *
     * @param userName 用户名
     * @return 分页对象
     */
    public DeviceInfoResponse devices(String userName, String deviceStatus) {

        return new TCAClient().findAccountDevices(userName, deviceStatus);

    }

    /**
     * 申请绑定二维码
     *
     * @param userName 帐号
     * @return 二维码申请结果
     */
    public ApplyQrCodeResponse applyQrCode(String userName) {

        return new TCAClient().applyQrCode(BusinessTypeEnum.DEVICE_BIND, env.getProperty("bind.granted"),
                env.getProperty("bind.localAuth"),
                userName + ":::", "绑定帐号", env.getProperty("bind.callback"));

//        TCAClientRequest request2 = TCAClientRequest.applyTCALocation(ConfigResource.tcaHost + "/grant/mobileAuthorize")
//                .setCredentialsProvider(new DefaultCredentialProvider(ConfigResource.clientId))
//                .addBodyParameter(CLIENT_ID, ConfigResource.clientId)
//                .addBodyParameter("tcad", Base64.encodeBase64String(("1&" + env.getProperty("bind.granted") + "&" + env.getProperty("bind.localAuth") +
//                        "&" + userName + ":::").getBytes()))
//                .addBodyParameter("response_type", "code")
//                .addBodyParameter("businessName", "绑定帐号")
//                .addBodyParameter("redirect_uri", env.getProperty("bind.callback"))
//                .addHeaderParameter(TCAHeaders.CONTENT_TYPE, HEADER_TYPE)
//                .buildMessage();
//
//        TCAClientResponse response2 = new URLConnectionClient().execute(request2, HttpMethod.POST, TCAClientResponse.class);
//
//        if (response2.getResponseCode() == 200) {
//            ApplyQrCodeResponse commonResponse;
//            try {
//                commonResponse = GsonUtils.getInstance().fromJson(response2.getBody(), ApplyQrCodeResponse.class);
//            } catch (JsonSyntaxException e) {
//                throw new NovException(e.getMessage(), e.getCause());
//            }
//            return commonResponse;
//        }
//        return null;

    }

    /**
     * 调用TCA接口获取二维码扫描状态
     *
     * @param scode 请求参数
     * @return 二维码扫描结果
     */
    public QrCodeStatusResponse qrStatus(String scode) {
        TCAClientRequest request2 = TCAClientRequest.applyTCALocation(ConfigResource.tcaInnerHost + "/grant/mobileStatus")
                .setCredentialsProvider(new DefaultCredentialProvider(ConfigResource.clientId))
                .addBodyParameter(CLIENT_ID, ConfigResource.clientId)
                .addBodyParameter("tempData", scode)
                .addHeaderParameter(TCAHeaders.CONTENT_TYPE, HEADER_TYPE)
                .buildMessage();

        TCAClientResponse response2 = new URLConnectionClient().execute(request2, HttpMethod.POST, TCAClientResponse.class);

        if (response2.getResponseCode() == 200) {
            QrCodeStatusResponse statusResponse;
            try {
                statusResponse = GsonUtils.getInstance().fromJson(response2.getBody(), QrCodeStatusResponse.class);
            } catch (JsonSyntaxException e) {
                throw new NovException(e.getMessage(), e.getCause());
            }
            return statusResponse;
        }

        return null;
    }

    /**
     * 解除帐号与设备绑定关系
     *
     * @param account  帐号
     * @param deviceId 设备
     * @return 操作结果
     */
    public CommonResponse release(String account, String deviceId) {
        TCAClientRequest request2 = TCAClientRequest.applyTCALocation(ConfigResource.tcaInnerHost + "/device/unbindAccount")
                .setCredentialsProvider(new DefaultCredentialProvider(ConfigResource.clientId))
                .addBodyParameter(CLIENT_ID, ConfigResource.clientId)
                .addBodyParameter("account", account)
                .addBodyParameter("device_id", deviceId)
                .addHeaderParameter(TCAHeaders.CONTENT_TYPE, HEADER_TYPE)
                .buildMessage();

        TCAClientResponse response2 = new URLConnectionClient().execute(request2, HttpMethod.POST, TCAClientResponse.class);

        if (response2.getResponseCode() == 200) {
            CommonResponse commonResponse;
            try {
                commonResponse = GsonUtils.getInstance().fromJson(response2.getBody(), CommonResponse.class);
            } catch (JsonSyntaxException e) {
                throw new NovException(e.getMessage(), e.getCause());
            }
            return commonResponse;
        }

        return null;
    }

}
